﻿using System;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Text.RegularExpressions;
using AutoMerge;
using AutoMergeCmd.Properties;

namespace AutoMergeCmd
{
    class Program
    {
        static int Main(string[] args)
        {
            writeSeparatorLine();
            Console.WriteLine(Resources.strHeaderBanner, 
                Assembly.GetExecutingAssembly().GetName().Version);
            Console.WriteLine(Resources.strCopyRights);
            writeSeparatorLine();

            #region Arguments check

            if (args.Length == 0)
            {
                showUsageHelp();
                return 1;
            }

            var outputFileName = selectArg(args, "o(output)?");
            if (string.IsNullOrWhiteSpace(outputFileName))
                return showArgumentError("o[utput]");

            var sourceFileName = selectArg(args, "s(ource)?");
            if (string.IsNullOrWhiteSpace(sourceFileName))
                return showArgumentError("s[ource]");

            var changedFileNames = selectArg(args, "c(hanged)?");
            if (string.IsNullOrWhiteSpace(changedFileNames))
                return showArgumentError("c[hanged]"); 

            #endregion

            var changedFiles = (from c in changedFileNames.Split(new[]{ ',' }, StringSplitOptions.RemoveEmptyEntries) 
                                where !string.IsNullOrWhiteSpace(c) select c.Trim().Replace(@"""", "")).ToArray();


            // вызов обработчика слияния из библиотеки AutoMerge
            try
            {
                Factory.MergeService.MergeChangedFiles(LogService.Instance, outputFileName, sourceFileName, changedFiles);
            }
            catch(Exception exception)
            {
                LogService.Instance.AddLogRecord(Resources.strError, exception.Message);
            }


            return 0;
        }

        private static void showUsageHelp()
        {
            Console.WriteLine(Resources.strUsageHelp);
            Console.ReadLine();
        }

        private static string selectArg(string[] args, string paramName)
        {
            return (from a in args where Regex.IsMatch(a, "/"+paramName+"=.*") 
                    select a.Substring(a.IndexOf("=")+1).Trim()).FirstOrDefault();
        }

        private static int showArgumentError(string argumentName)
        {
            LogService.Instance.AddLogRecord(Resources.strErrorArgNotFound, argumentName);
            writeSeparatorLine();
            showUsageHelp();
            return 1;
        }

        private static void writeSeparatorLine()
        {
            Console.WriteLine("".PadRight(79, '*'));
        }

    }
}
